package com.kuyu.wx;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
    @Autowired
    WxMpService wxMpService;
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnurl){
        returnurl="http://mym.nat300.top/wechat/userinfo";
        String gotourl=wxMpService.oauth2buildAuthorizationUrl(returnurl,WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(returnurl));
        log.info("【微信网页授权】获取code，result={}",gotourl);
        return "redirect:" + gotourl;
    }

    @GetMapping("/userinfo")
    public String userinfo(@RequestParam("code") String code,
                         @RequestParam("state") String returnurl){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken=new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken=wxMpService.oauth2getAccessToken(code);
            boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
            if(!valid){
                //刷新token
               wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
            }
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
        }
        String openid=wxMpOAuth2AccessToken.getOpenId();
        return "redirect:"+returnurl+"?openid="+openid;
    }

}
